<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2017/11/21
 * Time: 8:59
 */

namespace App\Modules\Channel\Models;

use DB;
use Illuminate\Database\Eloquent\Model;

class ChannelUser extends Model
{
    protected $table = 'channel_users';
    protected $fillable = ['name', 'pay_merchant_id', 'phone', 'nickname', 'person_in_charge_name', 'latest_login_time', 'remark', 'latest_login_ip', 'password', 'register_ip', 'is_enabled', 'distribution_manages_id', 'company_id', 'company_name'];

    static function getById($id)
    {
        return self::where('id', $id)->first();
    }

    static function getByPhone($phone)
    {
        return self::where('phone', $phone)->first();
    }

    static function getByIds($ids)
    {
        return self::whereIn('id', $ids)->select('id', 'phone', 'created_at')->paginate();
    }

    static function judgeLogin($phone, $pwd)
    {
        return self::where([['phone', '=', $phone], ['password', '=', $pwd]])
            ->where('is_enabled', 1)
            ->first();
    }

    static function getChannelIdsByChannelUserIds($channel_user_ids)
    {
        return self::join('distribution_channels', 'distribution_channels.channel_user_id', '=', 'channel_users.id')
            ->select(['distribution_channels.id'])
            ->whereIn('channel_users.id', $channel_user_ids)
            ->get();
    }

    static function getChannelInfosByChannelUserIds($channel_user_ids)
    {
        return self::join('distribution_channels', 'distribution_channels.channel_user_id', '=', 'channel_users.id')
            ->select('distribution_channels.id','distribution_channels.nickname','distribution_channels.site_nick_name')
            ->whereIn('channel_users.id', $channel_user_ids)
            ->get();
    }

    static function getChannelIdArray($channel_user_id)
    {
        $channel_user_ids = explode(',', $channel_user_id);
        $data = self::getChannelIdsByChannelUserIds($channel_user_ids);
        return $data->pluck('id');
    }

    static function getChannels($channel_user_id)
    {
        return self::join('distribution_channels', 'distribution_channels.channel_user_id', '=', 'channel_users.id')
            ->select('distribution_channels.id', 'distribution_channels.name', 'distribution_channels.nickname','distribution_channels.site_nick_name')
            ->where('channel_users.id', $channel_user_id)
            ->get();
    }
}